package com.basin.micro.uplaod.service.impl;

import com.basin.common.core.async.AsyncHelper;
import com.basin.common.core.exception.BasinException;
import com.basin.micro.uplaod.pojo.enums.ErrorTips;
import com.basin.micro.uplaod.service.UploadService;
import com.basin.micro.uplaod.task.UploadTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Service
@Slf4j
public class UploadServiceImpl implements UploadService {
    @Override
    public List<String> upload(MultipartFile[] files) {
        if (files == null || files.length == 0) {
            throw new BasinException(ErrorTips.FILE_NULL.generate());
        }
        // 组装任务
        var uploadTasks = new ArrayList<UploadTask>();
        for (MultipartFile file : files) {
            uploadTasks.add(new UploadTask(file));
        }
        // 线程执行
        AsyncHelper.executeWithResult(uploadTasks);
        // 循环所有结果
        var resList = new ArrayList<String>();
        for (UploadTask task : uploadTasks) {
            var curUrl = task.getResult();
            if (curUrl == null) {
                var fileName = task.getFileName();
                var reason = task.getE().getMessage();
                throw new BasinException(ErrorTips.UPLOAD_FAILED.generate(fileName, reason));
            }
            resList.add(curUrl);
        }
        return resList;
    }
}
